
from DailyBase import *
from AGDefines import *
import logging
from Log2File import *

logger = logging.getLogger(__name__)

RenWuColor = ('gold','Purple', 'Blue', 'Green', 'White')
ColorYu = {
    RenWuColor[0]: [(36, 105, 117), (56, 125, 137)],
    RenWuColor[1]: [(150, 40, 60), (190, 80, 100)],
    RenWuColor[2]: [(150, 80, 0), (190, 120, 20)],
    RenWuColor[3]: [(30, 137, 0), (60, 180, 20)],
    RenWuColor[4]: [(130, 120, 120), (180, 160, 160)],

}

class ShiMen(DailyBase):


    def __init__(self, enum):
        self.RCName = __name__
        self.LogHeader = self.RCName +str(enum.port)
        self.enum = enum
        self.started = False
        self.loadPrivateActions(self.areaDict, ShiMenActions)
        self.FailedTimes = 0
        self.shuaXinShu = -1
        logger.info("{} has {} actions".format(self.LogHeader, len(self.areaDict)))

        self.TuRect = []
        self.LeiRect = []
        self.RWclick = []

        stx = 116
        sty0 = 181
        sty1 = 280
        size_w = 136
        space_w = 8

        sty10 = 314
        sty11 = 333

        for i in range(4):
            x1 = stx + (size_w + space_w)*i
            x2 = x1 + size_w
            self.TuRect.append((x1, sty0, x2, sty1))
            self.LeiRect.append((x1 + 10, sty10, x2 - 10, sty11))
            self.RWclick.append([int((x1 + x2)/2), int((sty0 + sty1)/2), "RenWu"+str(i)])
    def reset(self):
        self.FailedTimes = 0
        self.shuaXinShu = -1

    def KaiShi(self):
        logger.info(".")
        Log2File.info(self.enum.port, "id {} 开始!!!".format(self.RCName))
        self.reset()
        self.begin()

    def process_private(self, img=None, data=None):

        logger.info("{} ".format(self.LogHeader))

        if self.status is STATUS_ZHANDOU:
            return

        if self.status is STATUS_ZHANDOU_SHOUDONG:
            self.enum.click(ZhanDouZiDong)
            return

        if self.feiZhanDouShu > 15:
            Log2File.info(self.enum.port, "id {} 超过15帧 没有动静了 结束!!!".format(self.RCName))
            self.stop()
            return

        if self.FailedTimes > 10:
            logger.info("FailedTimes({}) > 10, STOP!!!!".format(self.FailedTimes))
            Log2File.info(self.enum.port, "id {} 失败次数超过 10 !!!".format(self.RCName))
            self.stop()
            return

        if self.areaDict['KeJieRenWu'].detect(img, self.enum) < 10 or self.areaDict['YiWanRenWu'].detect(img, self.enum) < 10:
            ret,leixing = self.selectRenWu(img)

            if ret == STATUS_TRY_AGAIN:
                return
            elif ret == -1:
                logger.info("无法正确判断任务类型，似乎刚刚送完信")
                self.enum.click((394, 145, "Close Song Xin Dui Hua"))
                self.FailedTimes += 1
                return
            else:
                Log2File.info(self.enum.port, "{} 接到任务 {} !!!".format(self.RCName, leixing))
                logger.info("self.RWclick[ret] {}".format(self.RWclick[ret]))
                self.enum.click(self.RWclick[ret])
                #如果是金色任务，需要组队完成，接了以后，停止师门日常
                if leixing is RenWuColor[0]:
                    self.enum.click((394, 145, "Close Dui Hua"))
                    self.stop()


        elif gPublic.checkShangDian(self.enum, img) == STATUS_OK:
            return
        elif self.areaDict['ChuanShu'].detect(img, self.enum) < 10:
            self.enum.click(self.areaDict['ChuanShu'].click)
        elif self.areaDict['ChuanShuWan'].detect(img, self.enum) < 10:
            self.enum.click(self.areaDict['ChuanShuWan'].click)
        elif self.areaDict['JiaoXun'].detect(img, self.enum) < 10:
            self.enum.click(self.areaDict['JiaoXun'].click)
        return STATUS_OK

    def selectRenWu(self, img):
        LeixinList = []
        for i in range(4):
            tur = self.TuRect[i]
            leir = self.LeiRect[i]
            img1 = img[leir[1]:leir[3], leir[0]:leir[2]]
            leixing = self.checkLeiXing(img1)
            logger.info("{} {}".format(i, leixing))
            #cv2.imshow('img1' + str(i), img1)
            LeixinList.append(leixing)

        findIdx = -1
        leixing = ''
        for color in RenWuColor:
            #logger.info(color)
            if color in LeixinList:
                findIdx = LeixinList.index(color)
                leixing = color
                logger.info(findIdx)
                break

        if leixing == 'White':
            if self.shuaXinShu == -1:
                self.shuaXinShu = self.checkShuaXinShu(img)
            logger.info("left white queue, check 剩余刷新数:"+str(self.shuaXinShu))
            if self.shuaXinShu > 0:
                self.enum.click(self.areaDict['ShuaXinShu0'].click)
                self.shuaXinShu -= 1
                return STATUS_TRY_AGAIN,leixing
            else:
                return findIdx,leixing
        #cv2.waitKey()
        return findIdx,leixing



    def checkShuaXinShu(self, img):

        scores = []

        scores.append(self.areaDict['ShuaXinShu0'].detect(img, self.enum))
        scores.append(self.areaDict['ShuaXinShu1'].detect(img, self.enum))
        scores.append(self.areaDict['ShuaXinShu2'].detect(img, self.enum))
        scores.append(self.areaDict['ShuaXinShu3'].detect(img, self.enum))

        #logger.info(scores)

        minScore = np.min(scores)

        if minScore > 10:
            return 0

        return 3 - scores.index(minScore)

    def checkLeiXing(self, img):

        leixing = 'Finish'
        score = checkIsGray(img)

        #logger.info("some score {}".format(score))

        if score < 10:
            return leixing

        h,w,d = img.shape

        #print(h,w,d)
        img0 = img.copy()

        #print(img[0:5,0:5,:])

        sumBgr = [0, 0, 0]
        num = 0
        for i in range(h):
            for j in range(w):
                if (img[i, j, 0] == 90 and img[i, j, 1] == 36 and img[i, j, 2] == 6):
                    img0[i,j,:] = [0,0,0]
                else:
                    sumBgr += img[i,j]
                    num += 1

        meanBgr = sumBgr / num

        xxc = ((meanBgr[0] - meanBgr[1]), (meanBgr[0] - meanBgr[2]), (meanBgr[1] - meanBgr[2]))

        #imghsv = cv2.cvtColor(img0, cv2.COLOR_BGR2HLS)
        #score = cv2.mean(imghsv)
        #logger.info(score)


        for key in ColorYu:
            ret = self.compare(meanBgr, ColorYu[key][0],ColorYu[key][1])
            #logger.info("111  " + str(ret))
            if ret:
                #logger.info("123 "+key)
                leixing = key
                break

        if leixing == "Finish":
            logger.info("b g r mean {}, fangcha {}".format(meanBgr, xxc))

        return leixing

    def compare(self, bgr, small, large):
        res = (bgr > small) & (bgr < large)
        ret = res[0] & res[1] & res[2]
        #logger.info("{} {}".format(res, ret))
        return ret



